package com.tanhua.server.service;

import cn.hutool.core.util.ObjectUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.mongo.VideoApi;
import com.tanhua.dubbo.mongo.VoiceApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.FocusUser;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.mongo.Voice;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.PeachblossomVo;
import com.tanhua.model.vo.VideoVo;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SmallVideosService {

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Autowired
    private FdfsWebServer webServer;

    @DubboReference
    private VideoApi videoApi;
    @DubboReference
    private VoiceApi voiceApi;
    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 发布视频
     *
     * @param videoThumbnail
     * @param videoFile
     */
    public void saveVideos(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
        //1、封面图上传到阿里云OSS，获取地址
        String upload = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoFile.getInputStream());
        //2、视频上传到fdfs上，获取请求地址
        //获取文件的后缀名
        String originalFilename = videoFile.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        ////文件输入流，文件长度，文件后缀，元数据
        StorePath storePath = fastFileStorageClient.uploadFile(videoFile.getInputStream(),
                videoFile.getSize(), substring, null);
        String s = webServer.getWebServerUrl() + storePath.getFullPath();
        //3、创建Video对象，并设置属性
        Video video = new Video();
        video.setCreated(System.currentTimeMillis());
        video.setUserId(UserHolder.getUserId());
        video.setPicUrl(upload);
        video.setSeeType(1);
        video.setVideoUrl(s);
        video.setText("你是傻逼，你最帅！");
        //4、调用API完成保存
        videoApi.save(video);
    }

    /**
     * 小视频列表
     *
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult queryVideoList(Integer page, Integer pagesize) {
        //1、调用API查询分页数据 PageResult<Video>
        PageResult pageResult = videoApi.pageResult(page, pagesize);
        //2、获取分页对象中list集合  List<Video>
        List<Video> items = (List<Video>) pageResult.getItems();
        //3、一个Video转化成一个VideoVo对象
        List<VideoVo> collect = items.stream().map((item) -> {
            UserInfo byId = userInfoApi.findById(item.getUserId());
            VideoVo init = VideoVo.init(byId, item);
            //加入了作者关注功能，从redis判断是否存在关注的key，如果存在设置hasFocus=1
            if (redisTemplate.hasKey("followUser_" + UserHolder.getUserId() + "_" + item.getUserId())) {
                init.setHasFocus(1);
            }
            return init;
        }).collect(Collectors.toList());
        //4、替换PageResult中的list列表
        pageResult.setItems(collect);
        //5、构造返回值
        return pageResult;
    }

    //关注视频作者
    public void userFocus(Long followUserId) {
        //1、创建FollowUser对象，并设置属性
        FocusUser focusUser = new FocusUser();
        focusUser.setUserId(UserHolder.getUserId());
        focusUser.setFollowUserId(followUserId);
        focusUser.setCreated(System.currentTimeMillis());
        //2、调用API保存
        videoApi.saveFollowUser(focusUser);
        //3、将关注记录存入redis中
        String key = Constants.FOCUS_USER_KEY + UserHolder.getUserId();
        String hashKey = String.valueOf(followUserId);
        redisTemplate.opsForHash().put(key, hashKey, "1");
    }

    //取消关注视频作者
    public void userUnFocus(Long followUserId) {

        //1、调用API删除关注数据
        videoApi.deleteFollowUser(UserHolder.getUserId(), followUserId);
        //2、删除redis中关注记录
        String key = Constants.FOCUS_USER_KEY + UserHolder.getUserId();
        String hashKey = String.valueOf(followUserId);
        redisTemplate.opsForHash().delete(key, hashKey);
    }

    /**
     * 保存桃花传音
     *
     * @param soundFile
     */
    public void savePeachblossom(MultipartFile soundFile) throws IOException {
//        String originalFilename = soundFile.getOriginalFilename();
//        String substring = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
//        ////文件输入流，文件长度，文件后缀，元数据
//        StorePath storePath = fastFileStorageClient.uploadFile(soundFile.getInputStream(), soundFile.getSize(), substring, null);
//        String s = webServer.getWebServerUrl() + storePath.getFullPath();
        String s = ossTemplate.upload(soundFile.getOriginalFilename(), soundFile.getInputStream());
        Voice voice = new Voice();
        voice.setUserId(UserHolder.getUserId());
        voice.setVoiceUrl(s);
        voice.setStatus(1);
        voice.setCreated(System.currentTimeMillis());

        voiceApi.save(voice);
    }

    /**
     * 获取桃花传音
     *
     * @return
     */
    public PeachblossomVo getPeachblossom() {
        //当第一次获取传音时向redis中保存一条记录信息，记录获取次数，设置过期时间为一天
        String s = redisTemplate.opsForSet().pop(Constants.Peachblossom_count + UserHolder.getUserId());
        //每次从redis中获取次数判定是否等于0，当等于0时抛出异常限制接收语音
        if (StringUtils.isEmpty(s)) {
            redisTemplate.opsForSet().add(Constants.Peachblossom_count + UserHolder.getUserId(), String.valueOf(9));
            s = "10";
        }
        Integer value = Integer.valueOf(s);
        if (value <= 0) {
            throw new RuntimeException("当日次数已达上限！");
        }
        //当不为0时随机获取一条语音信息
        Voice voice = voiceApi.rundomPeachblossom(UserHolder.getUserId());
        if (ObjectUtil.isEmpty(voice)) {
            return null;
        }
        //封装用户信息返回vo对象
        value = value - 1;
        UserInfo byId = userInfoApi.findById(voice.getUserId());
        PeachblossomVo init = PeachblossomVo.init(byId, voice);
        init.setRemainingTimes(value);
        redisTemplate.opsForSet().add(Constants.Peachblossom_count + UserHolder.getUserId(), String.valueOf(value));
        voice.setStatus(0);
        voice.setReceiverId(UserHolder.getUserId());
        voiceApi.update(voice);
        return init;
    }
}